package com.cx.jmm;

import java.util.concurrent.TimeUnit;

/**
 * Author:CHENXIAOYI
 * Since:2020/9/16 10:33
 */
public class JmmTest {

    private  boolean flag = true;

    public  void testB(){
        flag = false;
        System.out.println("testB修改为false");
    }

    public  void testA(){
        System.out.println(Thread.currentThread().getName()+"开始执行");
        int i = 0;
        while (flag){
            i++; //1不能跳出

//            System.out.println("i++"); //2能 synchronized

//            shortWait(10000); //3不能
//            shortWait(50000); // 4能
//            try {
//                TimeUnit.NANOSECONDS.sleep(0); //5能
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

        }

        System.out.println(Thread.currentThread().getName()+"跳出循环"+i);
    }

    public static void main(String[] args) {
        JmmTest jmmTest = new JmmTest();

        new Thread(jmmTest::testA, "testA").start();

        try {
            TimeUnit.SECONDS.sleep(2);
            new Thread(jmmTest::testB, "testB").start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void shortWait(long time){
        long start = System.nanoTime();
        long end;
        do {
            end = System.nanoTime();
        }while (start + time >= end);
    }

}
